﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Net;

namespace SimoBotRewritten
{
    class URLTitle
    {
        BackgroundWorker bgwUrlTitle = new BackgroundWorker();



        public Parser ParseMachine;

        public URLTitle(Parser pr)
        {
            ParseMachine = pr;

            bgwUrlTitle.DoWork += new DoWorkEventHandler(bgwUrlTitle_DoWork);
        }

        string output ="";

        public Engine engine;

        public void RunURLTitle(string op, Engine eng)
        {
            engine = eng;
            output = op;
            if (!bgwUrlTitle.IsBusy)
                bgwUrlTitle.RunWorkerAsync(); 
        }

        private void bgwUrlTitle_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bgwUrlTitle = sender as BackgroundWorker;

            DoUrlTitle();


        }

        private void DoUrlTitle()
        {
            
            string URL = ParseMachine.GetUrl(output);

            WebClient client = new WebClient();
            string htmlCode = client.DownloadString(URL);


            string title = "";

            if (htmlCode.Contains("<title>"))
            {
                string[] htmlCodeSplitBiggerThan = htmlCode.Split('>');

                for (int i = 0; i < htmlCodeSplitBiggerThan.Length; i++)
                {
                    if (htmlCodeSplitBiggerThan[i].Contains("</title"))
                    {
                        title = htmlCodeSplitBiggerThan[i].ToString();
                        i = htmlCodeSplitBiggerThan.Length; // use break; to get out of the for loop... anyone?
                    }
                }

                title = title.Replace("</title", null).Trim().Replace("&ouml;", "ö").Replace("&auml;", "ä").Replace("&#45;", "-").Replace("&amp;", "&").Replace("&#39;", "'").Replace("&#8211;", "-").Replace("&#x202a;", "").Replace("&#x202c;", "").Replace("&rlm;", "").Replace("&#x202b;","");

            }

            else
            {
                title = "No title found";
            }

            if (title.Contains('\n'))        // You cannot say multiline stuff to irc so you have to split them to multiple messages
            {
                string[] titleArray = title.Split('\n');

                for (int i = 0; i < titleArray.Length; i++)
                {
                    engine.WriteToIrc(titleArray[i].ToString().Trim());
                }

            }
            else
            {
                engine.WriteToIrc(title);
            }
        }
    }
}
